package com.xg.utils;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.jsonwebtoken.lang.Collections;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author tzt
 */
@Slf4j
public class DDDUtils {
    /**
     * 复制MyBatis-Plus的Page对象
     *
     * @param sourcePage
     * @param clazz
     * @param <T>
     * @param <S>
     * @return
     * @throws InstantiationException
     * @throws IllegalAccessException
     */
    public static <T, S> Page<T> page(Page<S> sourcePage, Class<T> clazz) {
        if (sourcePage == null) {
            return null;
        }
        Page<T> targetPage = new Page<>();
        BeanUtils.copyProperties(sourcePage, targetPage, "record");

        if (!Collections.isEmpty(sourcePage.getRecords()) && clazz != null) {
            targetPage.setRecords((List<T>) collection(sourcePage.getRecords(), clazz));
        }

        return targetPage;
    }

    /**
     * 复制集合并指定类型
     *
     * @param sourceCollection
     * @param clazz
     * @param <T>
     * @param <S>
     * @return
     * @throws InstantiationException
     * @throws IllegalAccessException
     */
    public static <T, S> Collection<T> collection(Collection<S> sourceCollection, Class<T> clazz) {
        if (Collections.isEmpty(sourceCollection)) {
            Collection<T> t = new ArrayList<>();
            return t;
        }

        Collection targetCollection = null;
        try {
            targetCollection = sourceCollection.getClass().newInstance();
            for (S s : sourceCollection) {
                T t = clazz.newInstance();
                BeanUtils.copyProperties(s, t);
                targetCollection.add(t);
            }
        } catch (Exception e) {
            log.error("复制集合并指定类型异常", e);
        }finally {
            return targetCollection;
        }
    }
}
